_G.lua_extension = _G.lua_extension or {};
local lua_extension = _G.lua_extension;
local __lua_extension_directory__ = commonlib.FormatPath(commonlib.GetScriptDirectory() .. "/lua_extension");

local __cpp_require_modname__ = {
    ["coroutine"] = true,
    ["debug"] = true,
    ["io"] = true,
    ["file"] = true,
    ["math"] = true,
    ["os"] = true,
    ["package"] = true,
    ["string"] = true,
    ["table"] = true,
    ["utf8"] = true,
    ["socket.core"] = true,
    ["mime.core"] = true,
};

-- 加载模块
local __require_modules__ = {}; -- 模块缓存
function commonlib.require(module_name, module_directory)
    if (__cpp_require_modname__[module_name]) then return _G.require(module_name) end
    local filename = string.gsub(string.gsub(module_name, "%.lua$", ""), "%.", "/");
    local filepath = (module_directory or __lua_extension_directory__) .. "/" .. filename .. ".lua";
    local full_path = commonlib.FormatPath(filepath);
    -- print("require: " .. full_path);

    __require_modules__[full_path] = __require_modules__[full_path] or {};
    local __module__ = __require_modules__[full_path];
    if (__module__.__loaded__) then return __module__.__module__ end

    __module__.__filename__ = full_path;
    __module__.__directory__ = string.gsub(full_path, "([^\\/]*)$", "");
    __module__.__loaded__ = true;
    __module__.require = function(require_module_name) return commonlib.require(require_module_name, __module__.__directory__) end
    setmetatable(__module__, {__index = _G});

    local script_text = commonlib.GetScriptTextByFilePath(full_path);
    -- 加载脚本
    local func, errmsg = _G.load(script_text, full_path, "bt", __module__);
    if (not func) then
        print("load failed:" .. full_path, errmsg);
        return nil;
    end

    local ok, result = _G.pcall(func);
    if (not ok) then
        print("pcall failed:" .. full_path, result);
    else
        __module__.__module__ = result;
    end

    return __module__.__module__;
end

-- 加载json解码器
lua_extension.lunajson = commonlib.require("lunajson/lunajson");
lua_extension.LuaPanda = commonlib.require("LuaPanda");

_G.__debugger__ = function()
    package.path = 'C:/Users/xiaoyao/.vscode/extensions/stuartwang.luapanda-3.2.0/Debugger/?.lua;'.. package.path;
    lua_extension.LuaPanda.start('127.0.0.1', 8818);
end